﻿<%@ WebHandler Language="C#" Class="danweihuizong_chart" %>

using System;
using System.Web;
using System.Data;
using KeaoBase;
using ServiceStack.Redis;
using System.Configuration;
using System.Collections.Generic;
using System.Text;


public class danweihuizong_chart : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        try
        {
            string uid = context.Request.QueryString["uid"];
            string kid = context.Request.QueryString["kid"];
            if (!Auth.UserLogined(uid, kid))
            {
                context.Response.Write("{\"legend\":[],\"x\":[],\"data\":[]}");
                return;
            }
            string key = KeaoUtils.GetMD5Str(context.Request.Url.OriginalString.Replace(uid,"cache").Replace(kid,"cache"));
            using (IRedisClient redis = RedisClientPool.GetReadOnlyRedisClient())
            {
                if (redis != null)
                {
                    if (redis.ContainsKey(key))
                    {
                        context.Response.Write(redis.GetValue(key));
                        return;
                    }
                }
            }
            string zhanDian = context.Request.QueryString["zhandian"];
            string chengZhongLeiXing = context.Request.QueryString["chengzhongleixing"];
            string kaiShiShiJian = context.Request.QueryString["kaishishijian"];
            string jieShuShiJian = context.Request.QueryString["jieshushijian"];
            string wuLiaoMingCheng = context.Request.QueryString["wuliaomingcheng"];
            string xingHao = context.Request.QueryString["xinghao"];
            if (string.IsNullOrEmpty(zhanDian) || string.IsNullOrEmpty(chengZhongLeiXing) || string.IsNullOrEmpty(kaiShiShiJian) || string.IsNullOrEmpty(jieShuShiJian) || string.IsNullOrEmpty(wuLiaoMingCheng) || string.IsNullOrEmpty(xingHao))
            {
                context.Response.Write("{\"legend\":[],\"x\":[],\"data\":[]}");
                return;
            }
            if (wuLiaoMingCheng == "—请选择—")
            {
                context.Response.Write("{\"legend\":[],\"x\":[],\"data\":[]}");
                return;
            }

            BaseDataBase m_DB = System.Reflection.Assembly.Load("KeaoDataBase").CreateInstance(string.Format("KeaoDataBase.{0}", ConfigurationManager.AppSettings["数据库类型"])) as BaseDataBase;
            if (!m_DB.InitDataBase(ConfigurationManager.ConnectionStrings["DataSource"].ConnectionString))
            {
                context.Response.Write("{\"legend\":[],\"x\":[],\"data\":[]}");
                return;
            }
            else
            {
                string createCondition = m_DB.CreateAndCondition("chengzhongleixing", DataValueCommonType.字符串, chengZhongLeiXing, "", SearchConditionType.等于);
                if (zhanDian != "—全部—")
                {
                    createCondition += m_DB.CreateAndCondition("zhandian", DataValueCommonType.字符串, zhanDian, "", SearchConditionType.等于);
                }
                if (!string.IsNullOrEmpty(kaiShiShiJian) && !string.IsNullOrEmpty(jieShuShiJian))
                {
                    if (chengZhongLeiXing == "入库物料")
                    {
                        createCondition += m_DB.CreateAndCondition("pizhongshijian", DataValueCommonType.日期时间,string.Format("{0} 00:00:00",kaiShiShiJian),string.Format("{0} 23:59:59",jieShuShiJian), SearchConditionType.between);
                    }
                    else
                    {
                        createCondition += m_DB.CreateAndCondition("maozhongshijian", DataValueCommonType.日期时间, string.Format("{0} 00:00:00", kaiShiShiJian), string.Format("{0} 23:59:59", jieShuShiJian), SearchConditionType.between);
                    }
                }

                createCondition += m_DB.CreateAndCondition("wuliaomingcheng", DataValueCommonType.字符串, wuLiaoMingCheng, "", SearchConditionType.等于);

                if (!string.IsNullOrEmpty(xingHao) && xingHao != "—全部—")
                {
                    createCondition += m_DB.CreateAndCondition("xinghao", DataValueCommonType.字符串, xingHao, "", SearchConditionType.等于);
                }
                string tableCols = string.Empty;
                string groupCols = string.Empty;

                tableCols = "danweimingcheng,wuliaomingcheng,xinghao,count(id) as cheshu,sum(maozhong) as maozhong,sum(pizhong) as pizhong,sum(kouzhong) as kouzhong,sum(jingzhong) as jingzhong,sum(fahuozhongliang) as fahuozhongliang,sum(jisuanfangliang) as jisuanfangliang";
                groupCols = "danweimingcheng,wuliaomingcheng,xinghao";
                DataTable Dt = m_DB.GetDataTableByCondition("tbl_chengzhong", tableCols, null, createCondition, groupCols, null);

                tableCols = "danweimingcheng,count(id) as cheshu,sum(maozhong) as maozhong,sum(pizhong) as pizhong,sum(kouzhong) as kouzhong,sum(jingzhong) as jingzhong,sum(fahuozhongliang) as fahuozhongliang,sum(jisuanfangliang) as jisuanfangliang";
                groupCols = "danweimingcheng";
                DataTable DtDanWeiCount = m_DB.GetDataTableByCondition("tbl_chengzhong", tableCols, null, createCondition, groupCols, null);

                tableCols = "wuliaomingcheng,xinghao,count(id) as cheshu,sum(maozhong) as maozhong,sum(pizhong) as pizhong,sum(kouzhong) as kouzhong,sum(jingzhong) as jingzhong,sum(fahuozhongliang) as fahuozhongliang,sum(jisuanfangliang) as jisuanfangliang";
                groupCols = "wuliaomingcheng,xinghao";
                DataTable DtWuLiaoCount = m_DB.GetDataTableByCondition("tbl_chengzhong", tableCols, null, createCondition, groupCols, null);


                StringBuilder legendBuilder = new StringBuilder();
                StringBuilder xBuilder = new StringBuilder();
                List<ChartBar> chartBars = new List<ChartBar>();
                if (Dt.Rows.Count > 0)
                {
                    xBuilder.Append("\"x\":[");
                    foreach (DataRow row in DtDanWeiCount.Rows)
                    {
                        xBuilder.Append(string.Format("\"{0}\",", row["danweimingcheng"]));
                    }
                    xBuilder.Remove(xBuilder.Length - 1, 1);
                    xBuilder.Append("]");

                    legendBuilder.Append("\"legend\":[");
                    foreach (DataRow row in DtWuLiaoCount.Rows)
                    {
                        legendBuilder.Append(string.Format("\"{0}_{1}\",", row["wuliaomingcheng"], row["xinghao"]));
                        ChartBar newChartBar = new ChartBar();
                        newChartBar.WuLiaoMingCheng = string.Format("{0}", row["wuliaomingcheng"]);
                        newChartBar.XingHao = string.Format("{0}", row["xinghao"]);
                        newChartBar.SeriesName = string.Format("{0}_{1}", row["wuliaomingcheng"], row["xinghao"]);
                        chartBars.Add(newChartBar);
                    }
                    legendBuilder.Remove(legendBuilder.Length - 1, 1);
                    legendBuilder.Append("]");

                    foreach (DataRow row1 in DtDanWeiCount.Rows)
                    {
                        foreach (ChartBar chartBar in chartBars)
                        {
                            bool hasData = false;
                            foreach (DataRow row2 in Dt.Rows)
                            {
                                if (row1["danweimingcheng"].Equals(row2["danweimingcheng"]) && row2["wuliaomingcheng"].Equals(chartBar.WuLiaoMingCheng) && row2["xinghao"].Equals(chartBar.XingHao))
                                {
                                    chartBar.SeriesData.Append(string.Format("{0},", row2["jingzhong"]));
                                    hasData = true;
                                    break;
                                }
                            }
                            if (!hasData)
                            {
                                chartBar.SeriesData.Append("0,");
                            }
                        }
                    }

                    StringBuilder seriesBuilder = new StringBuilder();
                    foreach (ChartBar chartBar in chartBars)
                    {
                        seriesBuilder.Append(chartBar.ToString());
                        seriesBuilder.Append(",");
                    }
                    seriesBuilder.Remove(seriesBuilder.Length - 1, 1);
                    string responseJson = string.Format("{0}{1},{2},\"data\":[{3}]{4}", "{", legendBuilder.ToString(), xBuilder.ToString(), seriesBuilder.ToString(), "}");
                    using (IRedisClient redis = RedisClientPool.GetRedisClient())
                    {
                        if (redis != null)
                        {
                            redis.SetValue(key, responseJson, TimeSpan.FromMinutes(10.0));
                        }
                    }
                    context.Response.Write(responseJson);

                }
                else
                {
                    context.Response.Write("{\"legend\":[],\"x\":[],\"data\":[]}");
                }

            }
        }
        catch (Exception err)
        {
            KeaoUtils.LogTxt(string.Format("查询单位汇总图表异常。{0}", err.Message));
        }

    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}